using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Outpatient.ErrorCode;
using OutpatientApi.DTO;
using OutpatientApi.Methodimplementation.IServices;

namespace OutpatientApi.Controllers
{
    /// <summary>
    /// 咨询分类控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class ConsultationCategoryController : ControllerBase
    {
        private readonly IConsultationCategoryService _categoryService;
        private readonly ILogger<ConsultationCategoryController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="categoryService">咨询分类服务</param>
        /// <param name="logger">日志记录器</param>
        public ConsultationCategoryController(IConsultationCategoryService categoryService, ILogger<ConsultationCategoryController> logger)
        {
            _categoryService = categoryService;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有咨询分类
        /// </summary>
        /// <returns>咨询分类列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<ConsultationCategoryDto>>> GetAllCategories()
        {
            try
            {
                _logger.LogInformation("开始获取所有咨询分类API调用");

                var result = await _categoryService.GetAllCategoriesAsync();

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("获取所有咨询分类API调用成功，返回 {Count} 个分类", result.data?.Count ?? 0);
                }
                else
                {
                    _logger.LogWarning("获取所有咨询分类API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有咨询分类API调用异常");
                return new ApiResult<List<ConsultationCategoryDto>> { msg = "获取咨询分类时发生异常" };
            }
        }

        /// <summary>
        /// 根据咨询分类ID获取咨询信息列表
        /// </summary>
        /// <param name="categoryId">分类ID</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns>咨询信息列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<ConsultationDto>>> GetConsultationsByCategoryId(int categoryId, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                _logger.LogInformation("开始根据分类ID获取咨询信息API调用，分类ID：{CategoryId}，页码：{PageIndex}，页大小：{PageSize}", 
                    categoryId, pageIndex, pageSize);

                if (categoryId <= 0)
                {
                    _logger.LogWarning("分类ID无效：{CategoryId}", categoryId);
                    return new ApiResult<List<ConsultationDto>> { msg = "分类ID无效" };
                }

                if (pageIndex <= 0 || pageSize <= 0 || pageSize > 100)
                {
                    _logger.LogWarning("分页参数无效：页码={PageIndex}，页大小={PageSize}", pageIndex, pageSize);
                    return new ApiResult<List<ConsultationDto>> { msg = "分页参数无效" };
                }

                var result = await _categoryService.GetConsultationsByCategoryIdAsync(categoryId, pageIndex, pageSize);

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("根据分类ID获取咨询信息API调用成功，分类ID：{CategoryId}，返回 {Count} 条记录", 
                        categoryId, result.data?.Count ?? 0);
                }
                else
                {
                    _logger.LogWarning("根据分类ID获取咨询信息API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据分类ID获取咨询信息API调用异常，分类ID：{CategoryId}", categoryId);
                return new ApiResult<List<ConsultationDto>> { msg = "获取咨询信息时发生异常" };
            }
        }


        /// <summary>
        /// 根据健康咨询ID获取咨询详情信息列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<ConsultationDetailDto>>> SearchConsultationDetail([FromQuery] ParameterConsultationDetailDto dto)
        {
            try
            {
                return await _categoryService.SearchConsultationDetail(dto);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有咨询详情时发生异常");
                throw;
            }
        }

        /// <summary>
        /// 查询价目表信息（支持按标题和标签查找）
        /// </summary>
        /// <param name="dto">查询参数</param>
        /// <returns>价目表信息列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<PriceItemDto>>> SearchPriceItems([FromQuery] PriceItemQueryDto dto)
        {
            try
            {
                _logger.LogInformation("开始查询价目表信息API调用，标题：{Title}，标签：{Tag}，页码：{PageIndex}，页大小：{PageSize}", 
                    dto.Title, dto.Tag, dto.PageIndex, dto.PageSize);

                var result = await _categoryService.SearchPriceItemsAsync(dto);

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("查询价目表信息API调用成功，返回 {Count} 条记录", result.data?.Count ?? 0);
                }
                else
                {
                    _logger.LogWarning("查询价目表信息API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询价目表信息API调用异常，标题：{Title}，标签：{Tag}", dto.Title, dto.Tag);
                return new ApiResult<List<PriceItemDto>> { msg = "查询价目表信息时发生异常" };
            }
        }

        /// <summary>
        /// 查询优惠活动信息（支持与价目表连查）
        /// </summary>
        /// <param name="dto">查询参数</param>
        /// <returns>优惠活动信息列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<DiscountDto>>> SearchDiscounts([FromQuery] DiscountQueryDto dto)
        {
            try
            {
                _logger.LogInformation("开始查询优惠活动信息API调用，名称：{Name}，价目表标题：{PriceTitle}，页码：{PageIndex}，页大小：{PageSize}", 
                    dto.Name, dto.PriceTag, dto.PageIndex, dto.PageSize);

                var result = await _categoryService.SearchDiscountsAsync(dto);

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("查询优惠活动信息API调用成功，返回 {Count} 条记录", result.data?.Count ?? 0);
                }
                else
                {
                    _logger.LogWarning("查询优惠活动信息API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询优惠活动信息API调用异常，名称：{Name}，价目表标题：{PriceTitle}", dto.Name, dto.PriceTag);
                return new ApiResult<List<DiscountDto>> { msg = "查询优惠活动信息时发生异常" };
            }
        }

        /// <summary>
        /// 获取所有就医指南信息
        /// </summary>
        /// <returns>就医指南信息列表</returns>
        [HttpGet]
        public async Task<ApiResult<List<GuideDto>>> GetAllGuides()
        {
            try
            {
                _logger.LogInformation("开始获取所有就医指南信息API调用");

                var result = await _categoryService.GetAllGuidesAsync();

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("获取所有就医指南信息API调用成功，返回 {Count} 条记录", result.data?.Count ?? 0);
                }
                else
                {
                    _logger.LogWarning("获取所有就医指南信息API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有就医指南信息API调用异常");
                return new ApiResult<List<GuideDto>> { msg = "获取就医指南信息时发生异常" };
            }
        }

        /// <summary>
        /// 根据指南ID获取指南详情
        /// </summary>
        /// <param name="guideId">指南ID</param>
        /// <returns>指南详情</returns>
        [HttpGet]
        public async Task<ApiResult<GuideDto>> GetGuideById(int guideId)
        {
            try
            {
                _logger.LogInformation("开始根据指南ID获取指南详情API调用，指南ID：{GuideId}", guideId);

                if (guideId <= 0)
                {
                    _logger.LogWarning("指南ID无效：{GuideId}", guideId);
                    return new ApiResult<GuideDto> { msg = "指南ID无效" };
                }

                var result = await _categoryService.GetGuideByIdAsync(guideId);

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("根据指南ID获取指南详情API调用成功，指南ID：{GuideId}，标题：{Title}", 
                        guideId, result.data?.Title);
                }
                else
                {
                    _logger.LogWarning("根据指南ID获取指南详情API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据指南ID获取指南详情API调用异常，指南ID：{GuideId}", guideId);
                return new ApiResult<GuideDto> { msg = "获取指南详情时发生异常" };
            }
        }

        /// <summary>
        /// 新增用户收藏
        /// </summary>
        /// <param name="dto">新增收藏参数</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<ApiResult<bool>> AddUserCollection([FromBody] AddUserCollectionDto dto)
        {
            try
            {
                _logger.LogInformation("开始新增用户收藏API调用，用户ID：{UserId}，指南ID：{GuideId}，项目类型：{ItemType}", 
                    dto.UserId, dto.GuideId, dto.ItemType);

                // 参数验证
                if (dto.UserId <= 0)
                {
                    _logger.LogWarning("用户ID无效：{UserId}", dto.UserId);
                    return new ApiResult<bool> { msg = "用户ID无效" };
                }

                if (dto.GuideId <= 0)
                {
                    _logger.LogWarning("指南ID无效：{GuideId}", dto.GuideId);
                    return new ApiResult<bool> { msg = "指南ID无效" };
                }

                if (string.IsNullOrWhiteSpace(dto.ItemType))
                {
                    _logger.LogWarning("项目类型不能为空");
                    return new ApiResult<bool> { msg = "项目类型不能为空" };
                }

                var result = await _categoryService.AddUserCollectionAsync(dto);

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("新增用户收藏API调用成功，用户ID：{UserId}，指南ID：{GuideId}", dto.UserId, dto.GuideId);
                }
                else
                {
                    _logger.LogWarning("新增用户收藏API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增用户收藏API调用异常，用户ID：{UserId}，指南ID：{GuideId}", dto.UserId, dto.GuideId);
                return new ApiResult<bool> { msg = "新增收藏时发生异常" };
            }
        }

        /// <summary>
        /// 检查用户是否已收藏指定项目
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="guideId">指南ID</param>
        /// <param name="itemType">项目类型</param>
        /// <returns>是否已收藏</returns>
        [HttpGet]
        public async Task<ApiResult<bool>> CheckUserCollection(int userId, int guideId, string itemType)
        {
            try
            {
                _logger.LogInformation("开始检查用户收藏状态API调用，用户ID：{UserId}，指南ID：{GuideId}，项目类型：{ItemType}", 
                    userId, guideId, itemType);

                if (userId <= 0)
                {
                    _logger.LogWarning("用户ID无效：{UserId}", userId);
                    return new ApiResult<bool> { msg = "用户ID无效" };
                }

                if (guideId <= 0)
                {
                    _logger.LogWarning("指南ID无效：{GuideId}", guideId);
                    return new ApiResult<bool> { msg = "指南ID无效" };
                }

                if (string.IsNullOrWhiteSpace(itemType))
                {
                    _logger.LogWarning("项目类型不能为空");
                    return new ApiResult<bool> { msg = "项目类型不能为空" };
                }

                var result = await _categoryService.CheckUserCollectionAsync(userId, guideId, itemType);

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("检查用户收藏状态API调用成功，用户ID：{UserId}，指南ID：{GuideId}，已收藏：{IsCollected}", 
                        userId, guideId, result.data);
                }
                else
                {
                    _logger.LogWarning("检查用户收藏状态API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查用户收藏状态API调用异常，用户ID：{UserId}，指南ID：{GuideId}", userId, guideId);
                return new ApiResult<bool> { msg = "检查收藏状态时发生异常" };
            }
        }

        /// <summary>
        /// 取消用户收藏
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="guideId">指南ID</param>
        /// <param name="itemType">项目类型</param>
        /// <returns>操作结果</returns>
        [HttpDelete]
        public async Task<ApiResult<bool>> RemoveUserCollection(int userId, int guideId, string itemType)
        {
            try
            {
                _logger.LogInformation("开始取消用户收藏API调用，用户ID：{UserId}，指南ID：{GuideId}，项目类型：{ItemType}", 
                    userId, guideId, itemType);

                if (userId <= 0)
                {
                    _logger.LogWarning("用户ID无效：{UserId}", userId);
                    return new ApiResult<bool> { msg = "用户ID无效" };
                }

                if (guideId <= 0)
                {
                    _logger.LogWarning("指南ID无效：{GuideId}", guideId);
                    return new ApiResult<bool> { msg = "指南ID无效" };
                }

                if (string.IsNullOrWhiteSpace(itemType))
                {
                    _logger.LogWarning("项目类型不能为空");
                    return new ApiResult<bool> { msg = "项目类型不能为空" };
                }

                var result = await _categoryService.RemoveUserCollectionAsync(userId, guideId, itemType);

                if (result.code == ApiREunm.Ok)
                {
                    _logger.LogInformation("取消用户收藏API调用成功，用户ID：{UserId}，指南ID：{GuideId}", userId, guideId);
                }
                else
                {
                    _logger.LogWarning("取消用户收藏API调用失败：{Message}", result.msg);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "取消用户收藏API调用异常，用户ID：{UserId}，指南ID：{GuideId}", userId, guideId);
                return new ApiResult<bool> { msg = "取消收藏时发生异常" };
            }
        }

        /// <summary>
        /// 健康检查接口
        /// </summary>
        /// <returns>健康状态</returns>
        [HttpGet]
        public ApiResult<string> Health()
        {
            var result = new ApiResult<string>();
            result.success("OK", "咨询分类服务正常运行");
            return result;
        }
    }
} 